package com.codingfly;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MeilisearchService {

    public static int count = 0;
    public static List list = new ArrayList();
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void testWrite() {
        long start = System.currentTimeMillis();
        deal(new File("/data/test-data-set/PixivNovel/"));
        long end = System.currentTimeMillis();
        logger.info("cost time   ===>>>   "+(end-start));
        logger.info(">>>>>>>>>>>>>>>>>>>>>finish<<<<<<<<<<<<<<<<<<<");
    }

    public static void deal(File file) {
        if (file.isDirectory()) {
            for (File f:file.listFiles()) {
                deal(f);
            }
        } else {
            if (file.getName().endsWith(".txt") && file.getName().contains("-meta")==false) {
                String content = FileUtil.readString(file, "utf-8");
                String fileIndex = file.getName().replace(".txt", "");
                Map<String, Object> bodyParams = new HashMap();
                bodyParams.put("id", Long.valueOf(fileIndex));
                bodyParams.put("content", content);
                list.add(bodyParams);
                if (list.size()>300) {
                    try {
                        long start = System.currentTimeMillis();
                        HttpResponse response = HttpRequest.of("http://localhost:7700/indexes/novels/documents?primaryKey=id")
                                .bearerAuth("meilisearchTencent1234$#@!")
                                .body(JSON.toJSONString(list))
                                .method(Method.POST)
                                .execute();
                        long end = System.currentTimeMillis();
                        list = new ArrayList();
                        logger.info("one request cost time:" + (end - start) + "ms, http status code:" + response.getStatus() + " response:" + response.body());
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                    try {
                        Thread.sleep(18000);
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                count++;
                logger.info("deal file count:" + count);
            }
        }
    }

}
